package com.github.wxiaoqi.security.crm.core.biz;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.wxiaoqi.security.auth.common.util.SnowFlake;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.msg.ResponseCode;
import org.apache.http.util.EntityUtils;
import com.github.wxiaoqi.security.crm.core.entity.CustomerBaseAuths;
import com.github.wxiaoqi.security.crm.core.mapper.CustomerBaseAuthsMapper;
import net.sf.json.JSONObject;

/**
 * 客户授权信息
 *
 * @author centerroot
 * @email ${email}
 * @date 2018-07-16 10:15:49
 */
@Service
public class CustomerBaseAuthsBiz extends BaseBiz<CustomerBaseAuthsMapper,CustomerBaseAuths> {

	private static final Logger logger = (Logger) LoggerFactory.getLogger(CustomerBaseAuthsBiz.class);

	@Autowired
	private CustomerBaseAuthsMapper customerBaseAuthsMapper;

	/**
	 * 微信小程序授权
	 * @param request
	 * @return
	 */
	public Map<String, Object> wechatMiniProgramAuth(Map<String, Object> request){
		logger.info("微信授权请求。。。。。。{}", request);
		Map<String, Object> response = new HashMap<String, Object>();
		String platformId = (String) request.get("platformId");
		String code = (String) request.get("code");

		StringBuilder url = new StringBuilder();
		url.append("https://api.weixin.qq.com/sns/jscode2session?");
		url.append("appid=wx8074fe89f3193208");
		url.append("&secret=daadda3f9013d8cad0c4ea6d78c53499");
		url.append("&js_code=").append(code);
		url.append("&grant_type=authorization_code");
		String data = null;
		try {
			logger.info("小程序获取openId第三方请求参数------{}", url.toString());
			data = wxSmallGetOpenId(url.toString());
		} catch (Exception e) {
			e.printStackTrace();
			response.put("code", "400101");
			response.put("msg", "小程序授权失败");
			logger.info("微信授权响应。。。。。。{}", response);
			return response;
		}
		logger.info("小程序获取openId第三方返回参数------{}", JSONObject.fromObject(data));
		JSONObject json = JSONObject.fromObject(data);
		String openId = String.valueOf(json.get("openid"));
		CustomerBaseAuths customerBaseAuths = new CustomerBaseAuths();
		customerBaseAuths.setPlatformId(platformId);
		customerBaseAuths.setCustomerType("CUST02");//用户
		customerBaseAuths.setAuthType("00");//登录授权
		customerBaseAuths.setAuthMethod("weixin");//微信
		customerBaseAuths.setIsthird("01");//第三方
		customerBaseAuths.setCredential(openId);
		CustomerBaseAuths selectAuthsInfo = customerBaseAuthsMapper.selectOne(customerBaseAuths);
		
		String customerId = null;
		if(null == selectAuthsInfo){
			//为空则进行授权
			customerBaseAuths.setCustomerId(String.valueOf(SnowFlake.getId()));
			customerBaseAuthsMapper.insert(customerBaseAuths);
			customerId = customerBaseAuths.getCustomerId();
		}else{
			customerId = selectAuthsInfo.getCustomerId();
		}
		
		response.put("openId", openId);
		response.put("customerId", customerId);
		response.put("code", ResponseCode.OK.getCode());
		response.put("msg", ResponseCode.OK.getMessage());
		logger.info("微信授权响应。。。。。。{}", response);
		return response;
	}
	
	/**
     * 小程序发送get请求 获取openId
     * 
     * @param url
     *            路径
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String wxSmallGetOpenId(String url) throws Exception {
    	String strResult = null; // get请求返回结果
    	CloseableHttpClient client = HttpClients.createDefault();
    	
    	HttpGet request = new HttpGet(url);// 发送get请求
    	CloseableHttpResponse response = null;
    	try {
    		response = client.execute(request);
    		// 请求发送成功，并得到响应
    		logger.info("★★★★★★★★★★★★★★★★★★★★★★★★http response code:"+response.getStatusLine().getStatusCode());
    		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
    			strResult = EntityUtils.toString(response.getEntity()); // 读取服务器返回过来的json字符串数据
    		} else {
    			logger.info("get请求提交失败:" + url);
    			return null;  
    		}
    	}catch (Exception e){
    		logger.error("请求失败");
    		throw new Exception("请求失败或者服务器错误");
    		
    	}
    	return strResult;
    }
}